import random
import time
from DrissionPage import Chromium
from DrissionPage import ChromiumOptions
from DrissionPage._units.actions import Actions


def jd_main(product: str, brand: str, min_price: int = None, max_price: int = None):
    co = ChromiumOptions()
    co.headless(True)
    co.set_user_agent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0')
    # 增强反检测设置
    #co.set_argument('--disable-blink-features=AutomationControlled')
    #co.set_argument('--no-sandbox')
    #co.set_argument('--disable-dev-shm-usage')
    co.set_argument('--window-size=1920,1080')
    cookie = 'shshshfpa=ccc0e9dc-6724-d3aa-02b0-6a1e4d1d338c-1756862957; shshshfpx=ccc0e9dc-6724-d3aa-02b0-6a1e4d1d338c-1756862957; __jdv=122270672%7Cdirect%7C-%7Cnone%7C-%7C1756862957489; mba_muid=1756862957488186319325; __jdu=1756862957488186319325; areaId=18; ipLoc-djd=1-72-55653-0; x-rp-evtoken=mGW9U4qbzsaBdCMe70m9pIwI60idFTu0XLN8A3JAJihFR_2CrPzqh8LyL5fh5Qsbh8qrHEglQHGqLU8FtBMOgQ%3D%3D; 3AB9D23F7A4B3C9B=MEZOBBHOYZVTUOUE22TBGBT6NAPARLWKZAEX6667WZT3KZXR7J5KMFMRRFNIWS4YVB6AXKGDYIOSJ64E4KQXDQL5DU; TrackID=1kkMDwjOPOuHBB9TmKkl6ows-Epca4u1-KZA1Hp7M4CBj4_1OC4Bm_oQDtx5h5Qjm3Pd1i1ousVcmBPweRGWdJ8w6vvJU8YCVdVUJ9luTqnmi5cue40HNiuqIEZiOfAz8; thor=65141B2142559E5AF86638F2AC90AD0531CE154FA240069DC65D5858B7A466F378D3D082CA19D4F2C325921FBF949DA53C49502665079A89C0E9A9E42E1F0A0E78D5F061E825D35B563564B814633D9E3C852F2858FB03014981E96CFAF90EE2EC4643A634AB98F2D662AD0CB5A0C475E543F4C7F31ECDE3F7ACD7FDC210CB983BA578617904B6CD0E57FEC5D1A6628E7E1CDB8FDA9C1F62AAADE090FB8E5985; light_key=AASBKE7rOxgWQziEhC_QY6ya2TMlWlYbdztO6K73TQkmEeeVWkSgi-8aIH7vgJxwHYhI9mMa; pinId=WUtzHRkB6NNlMTe394UPaw; pin=jd_bttWXoasiXwz; unick=u335gmx71exs4u; _tp=RXf2NAQ%2BZDvX3QbTBhHYeg%3D%3D; _pst=jd_bttWXoasiXwz; token=b592b8b0a569909e24128b4af8338aba,3,976038; jsavif=1; jsavif=1; 3AB9D23F7A4B3CSS=jdd03MEZOBBHOYZVTUOUE22TBGBT6NAPARLWKZAEX6667WZT3KZXR7J5KMFMRRFNIWS4YVB6AXKGDYIOSJ64E4KQXDQL5DUAAAAMZBWH2Q4YAAAAACQBH5VSUWXLZPUX; _gia_d=1; __jda=181111935.1756862957488186319325.1756862957.1756862957.1756869142.2; cn=0; flash=3_s2bJP2qthOpCCn5fv0nrznf1JSSLGTGw4h0xRb5ZpzsCxsd5DovHDHo8Ok43dv0izppei5bxjmdRLeNz07-Ve_W4DvWsC8Bkgnurdm_jK9kgItaaowmkphwV7Jo8y-QwHOVcPhhETHgyLVkWmjN0mZzW9-bFrpxTWeDeLyYH8IkFxrlHmbh3; o2State=; __jdc=181111935; __jdb=181111935.6.1756862957488186319325|2.1756869142; shshshfpb=BApXSB8KYDvxANkfMlWM9HrB5A2n224JWBhTHLnho9xJ1MlKiqo62; sdtoken=AAbEsBpEIOVjqTAKCQtvQu174h5YD6NPaE381GJKEhymUcSAvFBZtPyKF4pBJnXaNExe6o3Q8Go0UEt43jmCc64meKvpYepbKN-eZgd-BmTrCa3I4tW5yJmtWA'
    browser = Chromium(co)
    tab = browser.latest_tab
    # 初始化商品列表
    product_list = []
    try:
        tab.get("https://www.jd.com")
        tab.set.cookies(cookie)
        # 输入框
        tab.ele('#key', timeout=10).input(product)
        # 点击搜索
        tab.ele('.button', timeout=10).click()
        # 点击筛选
        tab.ele('xpath://*[@id="search-condition"]/div[3]/div[3]/div/div/div/div', timeout=5).click()
        # 点击展开
        tab.ele(
            'xpath://*[@id="search-condition"]/div[3]/div[3]/div/div/div[2]/div[2]/div/div[1]/div[1]/div[2]/div', timeout=5).click()
        # 获取品牌列表的父元素
        brand_father = tab.ele(
            'xpath://*[@id="search-condition"]/div[3]/div[3]/div/div/div[2]/div[2]/div/div[1]/div[1]/div[1]/div[2]/div[2]/div', timeout=5)
        # 获取品牌列表元素
        brand_list = brand_father.eles("._value-item_19o6w_23", timeout=5)
        for i in brand_list:
            if brand.lower() in i.text.lower():
                i.click()
                break
        time.sleep(random.uniform(1, 1.5))
        # 点击确认
        tab.ele('xpath://*[@id="search-condition"]/div[3]/div[3]/div/div/div[2]/div[2]/div/div[2]/div[1]', timeout=5).click()
        time.sleep(random.uniform(1, 1.5))
        # 鼠标悬停价格区间
        tab.ele('xpath://*[@id="search-condition"]/div[2]/div[1]/div[2]/div/div/div/div', timeout=5).hover()

        # 最低价格判断，输入
        # 如果有最低价
        if min_price:
            # 输入最低价格
            tab.ele('._common-input__inner_p5qp6_4', timeout=5).input(min_price)
        # 如果没有最低价
        else:
            if max_price < 1000:
                min_price = round(max_price * 0.5)
            else:
                min_price = round(max_price * 0.7)
            # print(min_price)
            # 输入最低价格
            tab.ele('._common-input__inner_p5qp6_4', timeout=5).input(min_price)

        # 如果有最高价，输入最高价
        if max_price:
            # print(max_price)
            tab.eles('._common-input__inner_p5qp6_4', timeout=5)[-1].input(max_price)

        # 点击确认
        tab.ele('._common-button_1wphn_1 _common-button--primary_1wphn_20 _common-button--small_1wphn_13 _common-button--block_1wphn_24', timeout=5).click()

        time.sleep(random.uniform(1, 1.5))
        # 点击销量
        tab.ele('xpath://*[@id="search-condition"]/div[2]/div[1]/div[1]/div[2]/div', timeout=5).click()

        # 滚动屏幕下滑1000像素
        time.sleep(random.uniform(1, 1.5))
        ac = Actions(tab)
        ac.scroll(1000)
        time.sleep(random.uniform(1, 1.5))
        # tab.get_screenshot(
        #     path='tmp',
        #     name='截图.png',
        #     full_page=True
        # )

        # 获取商品信息的父元素
        product_father = tab.ele('._goodsContainer_f6icl_1 plugin_goodsContainer', timeout=5)
        # 获取商品信息
        for i in product_father.eles('._wrapper_2xp6d_3 plugin_goodsCardWrapper _row_6_2xp6d_13', timeout=5):
            # 获取商品信息
            product_data = {
                "title": i.ele('._wrapper_8g5fc_1').attr('title'),
                "img": i.ele('._img_18s24_1').attr("src"),
                # "store": i.ele('._name_d19t5_35').child().text,
                "price": i.ele('._price_1tn4o_13').text,
                "sales": i.ele('._goods_volume_1xkku_1').text,
                "href": f'https://item.jd.com/{i.attr("data-sku")}.html'
            }
            product_list.append(product_data)
        # print(product_list[:2])
        return product_list[:15]
    except Exception as e:
        print(e)
        browser.quit()
        return product_list[:15]
    finally:
        browser.quit()


if __name__ == '__main__':
    data = jd_main('牙膏', '洁', max_price=50)
    print(data)
